<?php

/**
 * OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures
 * all the essential functionalities required for any enterprise.
 * Copyright (C) 2006 OrangeHRM Inc., http://www.orangehrm.com
 *
 * OrangeHRM is free software; you can redistribute it and/or modify it under the terms of
 * the GNU General Public License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * OrangeHRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program;
 * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA
 */

if('ROOT_PATH'==ROOT_PATH){
	
}

require_once ROOT_PATH . '/lib/exception/ExceptionHandler.php';
require_once ROOT_PATH . '/lib/common/FormCreator.php';
require_once ROOT_PATH . '/lib/common/authorize.php';
require_once ROOT_PATH . '/lib/common/TemplateMerger.php';
require_once ROOT_PATH . '/lib/common/AjaxCalls.php';

require_once ROOT_PATH . '/lib/models/maintenance/UserGroups.php';
require_once ROOT_PATH . '/lib/models/maintenance/Users.php';
require_once ROOT_PATH . '/lib/models/maintenance/Rights.php';
require_once ROOT_PATH . '/lib/models/eimadmin/CountryInfo.php';
require_once ROOT_PATH . '/lib/models/eimadmin/ProvinceInfo.php';
require_once ROOT_PATH . '/lib/models/eimadmin/JobTitle.php';
require_once ROOT_PATH . '/lib/models/eimadmin/GenInfo.php';
require_once ROOT_PATH . '/lib/models/hrfunct/EmpInfo.php';
require_once ROOT_PATH . '/lib/models/recruitment/JobVacancy.php';
require_once ROOT_PATH . '/lib/models/news/News.php';//Chinh Nguyen add
require_once ROOT_PATH . '/lib/models/recruitment/JobApplication.php';
require_once ROOT_PATH . '/lib/models/recruitment/JobApplicationEvent.php';
require_once ROOT_PATH . '/lib/models/recruitment/RecruitmentMailNotifier.php';
require_once ROOT_PATH . '/lib/models/recruitment/RecruitmentAuthManager.php';
require_once ROOT_PATH . '/lib/extractor/recruitment/EXTRACTOR_ViewList.php';
require_once ROOT_PATH . '/lib/extractor/news/EXTRACTOR_newslist.php';
require_once ROOT_PATH . '/lib/extractor/news/EXTRACTOR_news.php';
require_once ROOT_PATH . '/lib/extractor/recruitment/EXTRACTOR_JobVacancy.php';
require_once ROOT_PATH . '/lib/extractor/recruitment/EXTRACTOR_JobApplication.php';
require_once ROOT_PATH . '/lib/extractor/recruitment/EXTRACTOR_JobApplicationEvent.php';
require_once ROOT_PATH . '/lib/extractor/recruitment/EXTRACTOR_ScheduleInterview.php';

/**
 * Controller for recruitment module
 */
class NewsController {

	private $authorizeObj;

    /**
     * Constructor
     */
    public function __construct() {
        if (isset($_SESSION) && isset($_SESSION['fname']) ) {
			$this->authorizeObj = new authorize($_SESSION['empID'], $_SESSION['isAdmin']);
        }
    }

    /**
     * Handle incoming requests
     * @param String code Recruit code
     */
    public function handleRequest($code) {

		if (empty($code) ) {
			trigger_error("Invalid Action " . $_GET['action'], E_USER_NOTICE);
			return;
		}
		/*
		$tempAction =null;
		if(!isset($_GET['action']))
			$tempAction ="List";
		else
			$tempAction= $_GET['action'];
		*/
		switch ($code) {

			case 'Vacancy' :
				$viewListExtractor = new EXTRACTOR_newsList();

	            switch ($_GET['action']) {

	                case 'List' :
	                	$searchObject = $viewListExtractor->parseSearchData($_POST, $_GET);
	                    $this->_viewListNews($searchObject);
	                    break;
	                case 'News' :
	                	$searchObject = $viewListExtractor->parseSearchData($_POST, $_GET);
	                    $this->_viewListNewsByType($searchObject,1);
	                    break;
	                case 'Event' :
	                	$searchObject = $viewListExtractor->parseSearchData($_POST, $_GET);
	                    $this->_viewListNewsByType($searchObject,2);
	                    break;
	                case 'Annoucement' :
	                	$searchObject = $viewListExtractor->parseSearchData($_POST, $_GET);
	                    $this->_viewListNewsByType($searchObject,3);
	                    break;
					case 'Level' :	                	
	                    $this->_viewListLevel();
	                    break;
	                case 'View' :
	                	$id = isset($_GET['id'])? $_GET['id'] : null;
	                	$this->_viewNews($id);
						break;
						
					 case 'Edit' :
	                	$id = isset($_GET['id'])? $_GET['id'] : null;
	                	$this->_editNews($id);
						break;

	                case 'ViewAdd' :
	                	$this->_viewAddNews();
	                	break;

					case 'Add' :
						$extractor = new EXTRACTOR_News();
						$news = $extractor->parseData($_POST);
						$this->_addNews($news);
						break;

					case 'Update' :
						$extractor = new EXTRACTOR_News();
						$news = $extractor->parseUpdateData($_POST);
						$this->_updateNews($news);
						break;

	                case 'Delete' :
	                    $ids = $_POST['chkID'];
	                    $this->_deleteNews($ids);
	                	break;
	            }
                break;

	    }
    }
	
	/**
	 * Generic method to display a list
	 * @param int $pageNumber Page Number
	 * @param int $count Total number of results
	 * @param Array $list results (in current page)
	 */

	private function _viewList($pageNumber, $count, $list) {

        $formCreator = new FormCreator($_GET, $_POST);
        $formCreator->formPath = '/newsview.php';
        $formCreator->popArr['currentPage'] = $pageNumber;
        $formCreator->popArr['list'] = $list;
        $formCreator->popArr['count'] = $count;
        $formCreator->display();

	}
	
	private function _viewListByType($pageNumber, $count, $list,$type) {

        $formCreator = new FormCreator($_GET, $_POST);
        $formCreator->formPath = '/newsview.php';
        $formCreator->popArr['currentPage'] = $pageNumber;
        $formCreator->popArr['list'] = $list;
        $formCreator->popArr['count'] = $count;
        $formCreator->popArr['type'] = $type;
        $formCreator->display();

	}
	
	private function _viewListAllByType($pageNumber, $countNews, $listNews,$typeNews, $countEvent, $listEvent,$typeEvent, $countAnnounce, $listAnnounce,$typeAnnounce,$countHot, $listHot,$typeHot) {

        $formCreator = new FormCreator($_GET, $_POST);
        $formCreator->formPath = '/newsview.php';
        $formCreator->popArr['currentPage'] = $pageNumber;
        $formCreator->popArr['listNews'] = $listNews;
        $formCreator->popArr['countNews'] = $countNews;
        $formCreator->popArr['typeNews'] = $typeNews;
        
        $formCreator->popArr['listEvent'] = $listEvent;
        $formCreator->popArr['countEvent'] = $countEvent;
        $formCreator->popArr['typeEvent'] = $typeEvent;
        
        $formCreator->popArr['listAnnounce'] = $listAnnounce;
        $formCreator->popArr['countAnnounce'] = $countAnnounce;
        $formCreator->popArr['typeAnnounce'] = $typeAnnounce;
        
        $formCreator->popArr['listHot'] = $listHot;
        $formCreator->popArr['countHot'] = $countHot;
         $formCreator->popArr['typeHot'] = $typeHot;
        
        $formCreator->display();

	}
	
	
private function _viewListAllByTypePublic($pageNumber, $countNews, $listNews,$typeNews, $countEvent, $listEvent,$typeEvent, $countAnnounce, $listAnnounce,$typeAnnounce) {

        $formCreator = new FormCreator($_GET, $_POST);
        $formCreator->formPath = '/login.php';
        $formCreator->popArr['currentPage'] = $pageNumber;
        $formCreator->popArr['listNews'] = $listNews;
        $formCreator->popArr['countNews'] = $countNews;
        $formCreator->popArr['typeNews'] = $typeNews;
        
        $formCreator->popArr['listEvent'] = $listEvent;
        $formCreator->popArr['countEvent'] = $countEvent;
        $formCreator->popArr['typeEvent'] = $typeEvent;
        
        $formCreator->popArr['listAnnounce'] = $listAnnounce;
        $formCreator->popArr['countAnnounce'] = $countAnnounce;
        $formCreator->popArr['typeAnnounce'] = $typeAnnounce;
        $formCreator->display();

	}

	/**
	* * View list of vacancies
	 * @param SearchObject Object with search parameters
	 */
	
    public function _viewListNews($searchObject) {

			/*
        	$list = News::getListForView($searchObject->getPageNumber(), $searchObject->getSearchString(), $searchObject->getSearchField(), $searchObject->getSortField(), $searchObject->getSortOrder());
        	$count = News::getCount($searchObject->getSearchString(), $searchObject->getSearchField());
        	$this->_viewList($searchObject->getPageNumber(), $count, $list);
			*/
    	
    		$listNews = News::getListByType(1,$searchObject->getPageNumber(), $searchObject->getSearchString(), $searchObject->getSearchField(), $searchObject->getSortField(), "DESC");
        	$countNews = News::getCount($searchObject->getSearchString(), $searchObject->getSearchField());
        	
        	$listEvent = News::getListByType(2,$searchObject->getPageNumber(), $searchObject->getSearchString(), $searchObject->getSearchField(), $searchObject->getSortField(), "DESC");
        	$countEvent = News::getCount($searchObject->getSearchString(), $searchObject->getSearchField());
        	
        	$listAnnounce = News::getListByType(3,$searchObject->getPageNumber(), $searchObject->getSearchString(), $searchObject->getSearchField(), $searchObject->getSortField(), "DESC");
        	$countAnnounce = News::getCount($searchObject->getSearchString(), $searchObject->getSearchField());
        	
        	$listHot = News::getListForView($searchObject->getPageNumber(), $searchObject->getSearchString(), $searchObject->getSearchField(), $searchObject->getSortField(), "DESC");
        	$countHot = News::getCount($searchObject->getSearchString(), $searchObject->getSearchField());
        	
        	$this->_viewListAllByType($searchObject->getPageNumber(), $countNews, $listNews,1,$countEvent, $listEvent,2,$countAnnounce, $listAnnounce,3,$countHot,$listHot,4);
		
    }
    
 	public function _viewListNewsPublic($searchObject) {

			/*
        	$list = News::getListForView($searchObject->getPageNumber(), $searchObject->getSearchString(), $searchObject->getSearchField(), $searchObject->getSortField(), $searchObject->getSortOrder());
        	$count = News::getCount($searchObject->getSearchString(), $searchObject->getSearchField());
        	$this->_viewList($searchObject->getPageNumber(), $count, $list);
			*/
 			$Obj = null;
    		$listNews = News::getListByType(1,$searchObject->getPageNumber(), $searchObject->getSearchString(), $searchObject->getSearchField(), $searchObject->getSortField(), "DESC");
        	$countNews = News::getCount($searchObject->getSearchString(), $searchObject->getSearchField());
        	
        	$listEvent = News::getListByType(2,$searchObject->getPageNumber(), $searchObject->getSearchString(), $searchObject->getSearchField(), $searchObject->getSortField(), "DESC");
        	$countEvent = News::getCount($searchObject->getSearchString(), $searchObject->getSearchField());
        	
        	$listAnnounce = News::getListByType(3,$searchObject->getPageNumber(), $searchObject->getSearchString(), $searchObject->getSearchField(), $searchObject->getSortField(), "DESC");
        	$countAnnounce = News::getCount($searchObject->getSearchString(), $searchObject->getSearchField());
        	
        	$Obj[0]=$listNews;
        	$Obj[1]=$listEvent;
        	$Obj[2]=$listAnnounce;
        	
        	return $Obj;
        	//$this->_viewListAllByTypePublic($searchObject->getPageNumber(), $countNews, $listNews,1,$countEvent, $listEvent,2,$countAnnounce, $listAnnounce,3);
		
    }
    
	private function _viewListNewsByType($searchObject,$type) {

		
        	$list = News::getListByType($type,$searchObject->getPageNumber(), $searchObject->getSearchString(), $searchObject->getSearchField(), $searchObject->getSortField(), "DESC");
        	$count = News::getCount($searchObject->getSearchString(), $searchObject->getSearchField());
        	$this->_viewListByType($searchObject->getPageNumber(), $count, $list,$type);
		
    }
	private function _viewListLevel() {
        	$formCreator = new FormCreator($_GET, $_POST);
        	$formCreator->formPath = '/levelview.php';        	
        	$formCreator->display();
        	
		
    }

	/**
	 * Delete vacancies with given IDs
	 * @param Array $ids Array with Vacancy ID's to delete
	 */
    private function _deleteNews($ids) {
		if ($this->authorizeObj->isAdmin()) {
			try {
        		$count = News::delete($ids);
        		$message = 'DELETE_SUCCESS';
			} catch (newsException $e) {
				$message = 'DELETE_FAILURE';
			}
            $this->redirect($message, '?newscode=Vacancy&action=List');//Chinh Nguyen change 'rectuitment' to 'recruitcode' 
		} else {
            $this->_notAuthorized();
		}
    }

	/**
	 * View add Vacancy page
	 */
	private function _viewAddNews() {
		if ($this->authorizeObj->isAdmin()) {
	    	$this->_editNews();
	    } else {
            $this->_notAuthorized();
		}
	}

    /**
     * View vacancy
     * @param int $id Id of vacancy. If empty, A new vacancy is shown
     */
    private function _viewNews($id = null) {

		$path = '/templates/news/news.php';

		try {
			
			if (empty($id)) {
				$news = new News();
			} else {
				$news = News::getNews($id);
			}
			//$objs['news_id'] = $news->getId();
			$objs['news_id'] = $id;
			$objs['news_title'] = $news->getNewsTitle();
			$objs['news_description'] = html_entity_decode($news->getNewsDescription());
			$objs['news_content'] = html_entity_decode($news->getNewsContent());
			$objs['news_type']="News";
			if($news->getNewsType()==1){
				$objs['news_type']="News";
			}elseif ($news->getNewsType()==2){
				$objs['news_type']="Event";
			}elseif($news->getNewsType()==3){
				$objs['news_type']="Announcement";
			}
				
			//$objs['news_type'] = $news->getNewsType();
			$objs['news_author'] = $news->getNewsAuthor();
			$objs['news_date'] = $news->getNewsDate();
			
			

			$template = new TemplateMerger($objs, $path);
			$template->display();
		} catch (NewsException $e) {
			$message = 'UNKNOWN_FAILURE';
            $this->redirect($message);
		}
    }
    
private function _editNews($id = null) {

		$path = '/templates/news/edit.php';

		try {
			
			if (empty($id)) {
				$news = new News();
			} else {
				$news = News::getNews($id);
			}
			$objs['news_id'] = $id;
			$objs['news_title'] = $news->getNewsTitle();
			$objs['news_description'] = $news->getNewsDescription();
			$objs['news_content'] = $news->getNewsContent();
			$objs['news_type']="News";
			if($news->getNewsType()==1){
				$objs['news_type']="News";
			}elseif ($news->getNewsType()==2){
				$objs['news_type']="Event";
			}elseif($news->getNewsType()==3){
				$objs['news_type']="Announcement";
			}
				
			//$objs['news_type'] = $news->getNewsType();
			$objs['news_author'] = $news->getNewsAuthor();
			$objs['news_date'] = $news->getNewsDate();
			
			

			$template = new TemplateMerger($objs, $path);
			$template->display();
		} catch (NewsException $e) {
			$message = 'UNKNOWN_FAILURE';
            $this->redirect($message);
		}
    }

    /**
     * Add vacancy to database
     * @param JobVacancy $vacancy Job Vacancy object to add
     */
    private function _addNews($news) {
		if ($this->authorizeObj->isAdmin()) {
			try {
				$news->save();
	        	$message = 'ADD_SUCCESS';
	        	$this->redirect($message, '?newscode=Vacancy&action=List');//Chinh Nguyen change 'rectuitment' to 'recruitcode'
			} catch (NewsException $e) {
				$message = 'ADD_FAILURE';
	        	$this->redirect($message);
			}
		} else {
            $this->_notAuthorized();
		}

    }

    /**
     * Add vacancy to database
     * @param JobVacancy $vacancy Job Vacancy object to add
     */
    private function _updateNews($news) {
		if ($this->authorizeObj->isAdmin()) {
			try {
				$news->save();
	        	$message = 'UPDATE_SUCCESS';
	        	$this->redirect($message, '?newscode=Vacancy&action=List');//Chinh Nguyen change 'rectuitment' to 'recruitcode'
			} catch (NewsException $e) {
				$message = 'UPDATE_FAILURE';
	        	$this->redirect($message);
			}
		} else {
            $this->_notAuthorized();
		}
    }

	/**
	 
    /**
     * View application details
     * @param int $id Application ID
     */
    private function _viewApplicationDetails($id) {
        $path = '/templates/recruitment/viewApplicationDetails.php';

        $objs['application'] = JobApplication::getJobApplication($id);

        $template = new TemplateMerger($objs, $path);
        $template->display();
    }

    /**
  
    /**
     * Add given event to application
     * @param JobApplicationEvent Job Application event with the details
     * @param int Event type
     */
    private function _saveApplicationEvent($event, $eventType) {

        $event->setEventType($eventType);
        $createdTime = date(LocaleUtil::STANDARD_DATETIME_FORMAT);
        $event->setCreatedTime($createdTime);
        $event->setCreatedBy($_SESSION['user']);
        //$event->setStatus($status);

        $event->save();
    }

    /**
     * Save the new values of passed Job Application Event
     */
    private function _editEvent($jobApplicationEvent) {
        try {
            $jobApplicationEvent->save();
            $message = 'UPDATE_SUCCESS';
        } catch (JobApplicationEventException $e) {
            $message = 'UPDATE_FAILURE';
        }
        $this->redirect($message);
    }

   
    public function createEmployeeFromApplication($jobApplication) {
		echo "create employee from application  here!";
		//error_log("create employee from application  here!",3,"C:/logtest.log");
        $empInfo = new EmpInfo();

        // main information
        $employeeId = $empInfo->getLastId();
        $empInfo->setEmployeeId($employeeId);
        $empInfo->setEmpLastName($jobApplication->getLastName());
        $empInfo->setEmpFirstName($jobApplication->getFirstName());
        $empInfo->setEmpMiddleName($jobApplication->getMiddleName());
        $result = $empInfo->addEmpMain();

        // contact information
        $empInfo->setEmpStreet1($jobApplication->getStreet1());
        $empInfo->setEmpStreet2($jobApplication->getStreet2());
        $empInfo->setEmpCity($jobApplication->getCity());
        $empInfo->setEmpProvince($jobApplication->getProvince());
        $empInfo->setEmpCountry($jobApplication->getCountry());
        $empInfo->setEmpZipCode($jobApplication->getZip());
        $empInfo->setEmpHomeTelephone($jobApplication->getPhone());
        $empInfo->setEmpMobile($jobApplication->getMobile());
        $empInfo->setEmpOtherEmail($jobApplication->getEmail());
        $result = $empInfo->updateEmpContact();

        // job information
        $vacancy = JobVacancy::getJobVacancy($jobApplication->getVacancyId());
        $empInfo->setEmpJobTitle($vacancy->getJobTitleCode());
        $empInfo->setEmpStatus(0);
        $empInfo->setEmpEEOCat(0);
        $result = $empInfo->updateEmpJobInfo();

        return $empInfo->getEmpId();
    }

	/**
	 * Redirect to given url or current page while displaying optional message
	 *
	 * @param String $message Message to display
	 * @param String $url URL
	 */
	public function redirect($message=null, $url = null) {

		if (isset($url)) {
			$mes = "";
			if (isset($message)) {
				$mes = "&message=";
			}
			$url=array($url.$mes);
			$id="";
		} else if (isset($message)) {
			preg_replace('/[&|?]+id=[A-Za-z0-9]*/', "", $_SERVER['HTTP_REFERER']);

			if (preg_match('/&/', $_SERVER['HTTP_REFERER']) > 0) {
				$message = "&message=".$message;
				$url = preg_split('/(&||\?)message=[A-Za-z0-9]*/', $_SERVER['HTTP_REFERER']);
			} else {
				$message = "?message=".$message;
			}

			if (isset($_REQUEST['id']) && !empty($_REQUEST['id']) && !is_array($_REQUEST['id'])) {
				$id = "&id=".$_REQUEST['id'];
			} else {
				$id="";
			}
		} else {
			if (isset($_REQUEST['id']) && !empty($_REQUEST['id']) && (preg_match('/&/', $_SERVER['HTTP_REFERER']) > 0)) {
				$id = "&id=".$_REQUEST['id'];
			} else if (preg_match('/&/', $_SERVER['HTTP_REFERER']) == 0){
				$id = "?id=".$_REQUEST['id'];
			} else {
				$id="";
			}
		}

		header("Location: ".$url[0].$message.$id);
	}

    /**
     * Show not authorized message
     */
    private function _notAuthorized() {
        trigger_error("Not Authorized!", E_USER_NOTICE);
    }
}
?>
